package com.letv.download.cpinfo;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.letv.bean.CpInfoBean;
import com.letv.common.ConnectionManager;
import com.letv.download.DownloadResult;
import com.letv.util.SQLUtil;
import com.letv.util.StringUtil;

/**
 * process and put cp_info into cbase
 */
public class CpInfoDataDownloadTask {

    /**
     * Logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CpInfoDataDownloadTask.class);

    /**
     * get cp info string for insert
     * @param cpInfoBean CpInfoBean, cp info pojo bean
     * @return String, return null if have errors
     */
    private static String getCpInsertString(CpInfoBean cpInfoBean) {
        if(null == cpInfoBean) {
            return null;
        }
        String result = null;
        try {
            StringBuffer resultBuffer = new StringBuffer("");
            resultBuffer.append(cpInfoBean.getId()).append(",");
            resultBuffer.append(StringUtil.formatString(cpInfoBean.getLetv_original_id())).append(",");
            resultBuffer.append(StringUtil.formatString(cpInfoBean.getName())).append(",");
            resultBuffer.append(StringUtil.formatString(cpInfoBean.getUrl())).append(",");
            resultBuffer.append(StringUtil.formatString(cpInfoBean.getDesc()));
            result = resultBuffer.toString();
        } catch(Exception e) {
            LOGGER.error("error to get cpInfo string for insert to database, cp_info id=" + cpInfoBean.getId());
            result = null;
        }
        return result;
    }

    /**
     * download data to local database for batch
     * @param listIndex int, index in the worker list.It's sign of this worker
     * @param beginId int, not include this id when select from data base
     * @param endId int, include this id when select from data base
     * @return DataProcessResult, this worker's data download infomation.return null while has errors
     */
    public DownloadResult downloadToLocalBatch(int listIndex, int beginId, int endId) {
        if(beginId >= endId) {
            return null;
        }

        ConnectionManager connectionManager = null;
        try {
            connectionManager = ConnectionManager.getInstance();
        } catch (Exception e) {
            LOGGER.error("worker " + listIndex + " cp_info fail to download date,connection get instance error!", e);
            return null;
        }

        Connection connectionFromLeso = null;
        try {
            connectionFromLeso = connectionManager.getConnectionFromLeso();
        } catch (Exception e) {
            LOGGER.error("worker " + listIndex + " cp_info fail to download date,connection get connectionFromLeso error!", e);
            return null;
        }

        List<CpInfoBean> cpInfoList = null;
        try {
            cpInfoList = SQLUtil.getCpInfoRange(connectionFromLeso, beginId, endId);
        } catch(Exception e) {
            LOGGER.error("worker " + listIndex + " has errors while select cp_info data from database", e);
        } finally{
            if(!SQLUtil.close(connectionFromLeso)) {
                LOGGER.error("fail to close connectionFromLeso when get cp_info range");
            }
        }

        if(null == cpInfoList || cpInfoList.size() == 0) {
            LOGGER.error("worker " + listIndex + "select none cp_info record from database");
            return null;
        }
        LOGGER.info("worker " + listIndex + "select " + cpInfoList.size() + " cp_info record from database");

        DownloadResult result = new DownloadResult();
        Connection connectionFromLocal = null;
        try {
            connectionFromLocal = connectionManager.getConnection();
            ArrayList<String> recordList = new ArrayList<String>();
            for(CpInfoBean cpInfoBean : cpInfoList) {
                LOGGER.info("download cp data to local database, id=" + cpInfoBean.getId());
                String record = CpInfoDataDownloadTask.getCpInsertString(cpInfoBean);
                if(null != record) {
                    recordList.add(record);
                }
            }
            if(null == recordList || recordList.size() == 0) {
                return null;
            }
            SQLUtil.insertSourceData(connectionFromLocal, "cp", recordList);
            result.setRecordsCnt(recordList.size());
            result.setFlag(true);
        } catch(Exception e) {
            LOGGER.error("worker " + listIndex + " has errors while insert data to local database", e);
        } finally{
            if(!SQLUtil.close(connectionFromLocal)) {
                LOGGER.error("fail to close connectionFromLocal");
            }
        }
        return result;
    }
}